/* 
Header,Payload  安全性相关
Signature  加密字符串
身份认证，将jwt放在http的Authorization字段当中
*/
const express = require('express')
const app = express();
const bodyParse = require('body-parser')
app.use(bodyParse.urlencoded({ extended: false }));
//定义密钥，用于加密和解密
const secretKey = 'name is Tan ming ^_^'
// 生成jwt字符串
const jwt = require('jsonwebtoken')
//解析jwt字符串以json格式输出
const { expressjwt } = require('express-jwt');
// const { send } = require('process');
//解析jwt字符，以api/开头的不需要访问权限，解析出来的字符挂载到req.user或者req.auth中
app.use(expressjwt({ secret: secretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }))

app.use((err, req, res, next) => {
  if (err.name == 'UnauthorizedError') {
    res.send({ status: 400, messgae: 'token失效' })
  } else {
    res.send({ status: 500, messgae: '未知错位' })
  }
})

//登录接口
app.post('/api/login', function (req, res) {
  const useInfo = req.body;
  // res.send(body)
  if (useInfo.username != 'admin' && userInfo.password != 0000) {
    res.send({
      stauts: 400,
      message: '登录失败'
    })
  } else {
    //登录成功，生产jwt字符串，并且通过token给客户端
    const tokenStr = jwt.sign(useInfo, secretKey, { expiresIn: '300s' });
    res.send({
      stauts: 200,
      message: '登录成功',
      token: tokenStr
    })
  }
})
// 获取信息,在客户端请求是需要在请求头上Authorization赋值为jwt字符串，并且以Bearer开头来进行解析
app.get('/admin/users', function (req, res) {
  console.log(req.auth);
  res.send({
    stauts: 200,
    message: '获取成功',
    info: req.auth
  })
})
app.listen(8082, () => {
  console.log('severing is running');
})